package com.mbcn.action;

import java.awt.image.BufferedImage;
import java.io.File;

import com.opensymphony.xwork2.ActionSupport;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.imgscalr.Scalr;

public class ImagesUpload extends ActionSupport {
	private File userImage;
	private String userImageContentType;
	private String userImageFileName;
	private String fileName;
	private String fileType;

	public String getFileType() {
		return fileType;
	}

	public void setFileType(String fileType) {
		this.fileType = fileType;
	}

	HttpServletRequest request = ServletActionContext.getRequest();

	public String execute() {
		try {
			Date now = new Date(); // java.util.Date, NOT java.sql.Date or
			// java.sql.Timestamp!
			String datetime = new SimpleDateFormat("yyyyMMddHHmmss")
					.format(now);
			String filePath = request.getSession().getServletContext()
					.getRealPath("/")+"imagesUserUploaded_tmp";
			
			String extension = this.userImageFileName
					.substring(this.userImageFileName.lastIndexOf("."));
			fileName = fileType + datetime
					+ extension;
			File fileToCreate = new File(filePath, fileName);
			//File fileToCreate = new File(filePath + fileName);
//Resize and crop
			BufferedImage img = null;
			BufferedImage scaledImage = null;
			BufferedImage dest;
			
				img = ImageIO.read(userImage);
				if(img.getWidth()>img.getHeight()){
					scaledImage = Scalr.resize(img, Scalr.Method.AUTOMATIC,
							Scalr.Mode.FIT_TO_HEIGHT, 280);
					 dest = scaledImage.getSubimage((scaledImage.getWidth()/2)-140, 0, 280, 280);
				}else {
					scaledImage = Scalr.resize(img, Scalr.Method.AUTOMATIC,
							Scalr.Mode.FIT_TO_WIDTH, 280);
					 dest = scaledImage.getSubimage(0, (scaledImage.getHeight()/2)-140, 280, 280);
				}
				
				ImageIO.write(dest, "JPG", fileToCreate);
				
				
				
			//FileUtils.copyFile(this.userImage, fileToCreate);
		} catch (Exception e) {
			e.printStackTrace();
			addActionError(e.getMessage());

			return INPUT;
		}
		return SUCCESS;
	}

	public File getUserImage() {
		return userImage;
	}

	public void setUserImage(File userImage) {
		this.userImage = userImage;
	}

	public String getUserImageContentType() {
		return userImageContentType;
	}

	public void setUserImageContentType(String userImageContentType) {
		this.userImageContentType = userImageContentType;
	}

	public String getUserImageFileName() {
		return userImageFileName;
	}

	public void setUserImageFileName(String userImageFileName) {
		this.userImageFileName = userImageFileName;
	}
	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

}